<?php

namespace App\Admin\Controllers;

use App\Admin\Renderable\UserTable;
use App\Admin\Repositories\Article;
use App\Models\ArticleCategory;
use App\Models\Message;
use App\Models\User;
use App\Services\TtsService;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;

class ArticleController extends AdminController
{
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new Article(['category:id,name','user:id,nickname,avatar']), function (Grid $grid) {
            $grid->model()->where('type',4);
            $grid->column('id')->sortable();
            $grid->column('sort');
            $grid->column('user.avatar','用户头像')->image('',80,80);
            $grid->column('user.nickname','用户昵称');
            $grid->column('stats')
                 ->using([1 => '原创',2 => '转载'])
                 ->label([1 => 'success',2 => 'primary']);
            $grid->column('category.name','分类');
            $grid->column('title');
            $grid->column('status')
                ->using([0 => '隐藏',1 => '显示'])
                ->label([0 => 'danger',1 => 'success']);
            $grid->column('audit_status')
                ->using([1 => '待审核',2 => '已通过',3 => '已拒绝'])
                ->label([1 => 'danger',2 => 'success',3 => 'warning']);
            $grid->column('created_at');
            $grid->column('updated_at')->sortable();
            $grid->fixColumns(1);

            $grid->filter(function (Grid\Filter $filter) {
                $filter->panel();
                $filter->like('title','标题')->width(3);
                $filter->equal('category_id')->select(ArticleCategory::getOption())->width(3);

            });
        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new Article(), function (Show $show) {
            $show->field('id');
            $show->field('sort');
            $show->field('user_id');
            $show->field('stats');
            $show->field('category_id');
            $show->field('title');
            $show->field('content');
            $show->field('status');
            $show->field('audit_status');
            $show->field('reject_reason');
            $show->field('created_at');
            $show->field('updated_at');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new Article(), function (Form $form) {
            $form->display('id');
            $form->number('sort')
                ->min(0)
                ->help('数字越小排序越靠前')
                ->required();


            $form->selectTable('user_id','用户')
                ->from(UserTable::make())
                ->model(User::class,'id','nickname');
            $form->radio('stats')
                 ->options([1 => '原创',2 => '转载'])
                 ->default(1)
                 ->required();
            $form->select('category_id')
                 ->options(ArticleCategory::getOption())
                 ->required();
            $form->text('title')
                 ->maxLength(255)
                 ->required();
            $form->image('cover','封面')
                 ->disk('oss')
                 ->autoUpload()
                 ->uniqueName()
                 ->removable(false)
                 ->saveFullUrl()
                  ->autoSave(false)
                 ->saving(function ($value){
                     return (string)$value;
                 });
            $form->editor('content')
                 ->disk('oss')
                 ->required();
            $form->radio('status')
                 ->options([1 => '显示',0 => '隐藏'])
                 ->default(1)
                 ->required();
            $form->radio('audit_status')
                ->options([1 => '待审核',2 => '已通过',3 => '已拒绝'])
                ->default(1)
                ->when(3,function (Form $form){
                    $form->textarea('reject_reason')
                        ->saving(function ($value){
                          return (string)$value;
                        })->rules('max:255',['max' => '最多500字']);
                })->required();
            //$form->hidden('task_id');
            $form->hidden('type');
            $form->saving(function (Form $form){
                $form->input('type',4);
            });


            $form->saved(function (Form $form,$result){
                if ($result){
                    if (!$form->model()->audit_time && $form->input('audit_status')==2){
                        $tts = new TtsService();
                        $task_id = $tts->ttsCreate(str_replace('&nbsp;','',strip_tags($form->input('content'))));
                        DB::table('articles')
                            ->where('id',$form->getKey())
                            ->update([
                                'audit_time' => date('Y-m-d'),
                                'task_id' => $task_id,
                            ]);

                        if ($form->input('user_id')){
                            $company_name = DB::table('firms')
                                ->where('user_id',$form->input('user_id'))
                                ->value('name');
                            if ($company_name){
                                Message::query()->create([
                                    'type' => 4,
                                    'content' => $company_name. '公司发布了新资讯'
                                ]);
                            }
                        }

                    }

                    if ($form->input('user_id') && $form->input('audit_status')==2){
                        event(new \App\Events\Message([
                            'user_id' =>  $form->input('user_id'),
                            'type' => 2,
                            'content' => '恭喜您发布的文章已通过审核'
                        ]));

                    }

                    if ($form->input('user_id') && $form->input('audit_status')==3){
                        event(new \App\Events\Message([
                            'user_id' =>  $form->input('user_id'),
                            'type' => 2,
                            'content' => '您发布的文章未通过审核'
                        ]));
                    }


                }
            });



            $form->display('created_at');
            $form->display('updated_at');
        });
    }
}
